package main

import (
	"encoding/json"
	"html/template"
	"log"
	"net/http"
	"math/rand"
	"fmt"
)

type Log struct {
	Name     string
	Password string
}

func home(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	t, _ := template.ParseFiles("./template/hello.html")
	t.Execute(w, nil)
}

func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method == "GET" {
		t, _ := template.ParseFiles("template/login.html")
		t.Execute(w, nil)
	} else {
		information := &Log{r.Form["username"][0], r.Form["Password"][0]}
		t, _ := template.ParseFiles("template/List.html")
		t.Execute(w, information)
	}
}

type test struct {
	ID int    `json:"id"`
	Content  string `json:"content"`
}

func api_test(w http.ResponseWriter, r *http.Request) {
	randnum := rand.Intn(1000)
	res := &test{ randnum, "Succeed!"}
	msg, _ := json.Marshal(res)
	w.Write(msg)
}

func main() {
	fmt.Println("Listen at 8080")
	http.HandleFunc("/", home)
	//测试静态文件服务
	http.Handle("/static/",
		http.StripPrefix("/static/",
			http.FileServer(http.Dir("static"))))
	//测试简单js访问
	http.HandleFunc("/api/test", api_test)
	//测试提交表单
	http.HandleFunc("/login", login)
	//设置监听的端口
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
